/*
 * Copyright 2008 Lucifer Lu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Shapes;
using SilverChart.Components;
using SilverChart.Configuration;
using SilverChart.Core.Log;
using SilverChart.Core.Resources;
using SilverChart.Util;

namespace SilverChart.LineChart {
    /// <summary>
    /// Description of LineChartModel.
    /// </summary>
    public partial class LineChartModel : CartesianCoordinateChart {
        private static Logger logger = Logger.GetLogger<LineChartModel>();

        private Path ChartLine;
        private GeometryGroup LinesGroup;
        private List<Path> ChartDots;
        private Double XOffset;

        private LineChartConfigurationWrapper Wrapper;

        public LineChartModel(Element data)
            : base(data) {
            Wrapper = new LineChartConfigurationWrapper(data);
            //Background = BrushHelper.GetSolidColorBrush("Yellow");

            if ((XAxis.AxisConfig as XAxis).LabelStartFromZero) {
                XOffset = 0;
            }
            else {
                XOffset = 1;
            }

            ChartDots = new List<Path>();

            ChartLine = Wrapper.ChartLine;
            PathGeometry pathGeometry = new PathGeometry();
            LinesGroup = new GeometryGroup();
            LinesGroup.FillRule = FillRule.EvenOdd;
            ChartLine.Data = LinesGroup;
            Children.Add(ChartLine);

            if (Wrapper.ShowTip || Wrapper.ShowDot) {
                for (Int32 i = 0; i < Wrapper.Values.Count; i++) {
                    Path chartDot = ProcessLineDot(Wrapper.Dot, Math.Round(Wrapper.Values[i], 10).ToString());
                    Children.Add(chartDot);
                    ChartDots.Add(chartDot);
                }
            }
        }

        private Path ProcessLineDot(Path chartDot, String tooltipString) {
            if (Wrapper.ShowDot) {
                chartDot.Stroke = (Brush)chartDot.Resources["ShowDot_Stroke"];
                chartDot.Stroke.Opacity = 0.8;
                chartDot.Fill = (Brush)chartDot.Resources["ShowDot_Fill"];
            }
            else {
                chartDot.Stroke = LineChartConfigurationWrapper.EmptyDotStroke;
                chartDot.Fill = LineChartConfigurationWrapper.EmptyDotFill;
            }

            if (Wrapper.ShowTip) {
                chartDot.Cursor = Cursors.Hand;
                ToolTipService.SetToolTip(chartDot, CreateToolTip(tooltipString));
                chartDot.MouseEnter += new MouseEventHandler(Tooltip_MouseEnter);
                chartDot.MouseLeave += new MouseEventHandler(Tooltip_MouseLeave);
            }
            else {
                chartDot.Cursor = Cursors.Arrow;
            }

            return chartDot;
        }

        private ToolTip CreateToolTip(string tooltipString) {
            ToolTip tip = new ToolTip();
            tip.HorizontalOffset = 5;
            tip.VerticalOffset = -35;
            tip.Opacity = 0.8;
            tip.Content = tooltipString;
            return tip;
        }

        public override List<LegendProperties> Legends {
            get {
                if (Wrapper.LegendName == null || Wrapper.LegendName.Trim().Length <= 0) {
                    return null;
                }

                return new List<LegendProperties>(){
                    new LegendProperties(this, Wrapper.LegendName, Wrapper.LineStroke, Wrapper.LineStroke)
                };
            }
        }

        void Tooltip_MouseLeave(object sender, MouseEventArgs e) {
            Path chartDot = sender as Path;
            if (chartDot != null) {
                if (!Wrapper.ShowDot) {
                    chartDot.Fill = LineChartConfigurationWrapper.EmptyDotFill;
                    chartDot.Stroke = LineChartConfigurationWrapper.EmptyDotStroke;
                }

                EllipseGeometry ellipse = (EllipseGeometry)chartDot.Data;
                ellipse.RadiusX = Wrapper.DotRadius;
                ellipse.RadiusY = Wrapper.DotRadius;
            }
        }

        void Tooltip_MouseEnter(object sender, MouseEventArgs e) {
            Path chartDot = sender as Path;
            if (chartDot != null) {
                EllipseGeometry ellipse = (EllipseGeometry)chartDot.Data;
                ellipse.RadiusX = Wrapper.DotRadius + 2;
                ellipse.RadiusY = Wrapper.DotRadius + 2;

                if (!Wrapper.ShowDot) {
                    chartDot.Fill = (Brush)chartDot.Resources["ShowDot_Fill"];
                    chartDot.Stroke = (Brush)chartDot.Resources["ShowDot_Stroke"];
                }
            }
        }

        public override string WidgetName {
            get {
                return "Line Chart Component";
            }
        }

        protected override Size MeasureOverride(Size availableSize) {
            logger.Debug("MeasureOverride():" + availableSize.ToString());
            Size aSize = new Size(Math.Min(availableSize.Width, 10000),
                Math.Min(availableSize.Height, 10000));
            return aSize;
        }

        protected override Size ArrangeOverride(Size finalSize) {
            logger.Debug("ArrangeOverride():" + finalSize.ToString());
            LinesGroup.Children.Clear();
            if (Wrapper.Values.Count >= 1) {
                LineGeometry currentLine = null;
                for (Int32 i = 0; i < Wrapper.Values.Count; i++) {
                    Double x = XAxis.MappingValueToAxis(i + XOffset);
                    Double y = YAxis.MappingValueToAxis(Wrapper.Values[i]);

                    if (i > 0) {
                        currentLine.EndPoint = new Point(x, y);
                        LinesGroup.Children.Add(currentLine);
                    }

                    if (i < Wrapper.Values.Count - 1) {
                        currentLine = new LineGeometry();
                        currentLine.StartPoint = new Point(x, y);
                    }

                    if (Wrapper.ShowTip || Wrapper.ShowDot) {
                        Path chartDot = ChartDots[i];
                        EllipseGeometry ellipse = (EllipseGeometry)chartDot.Data;
                        ellipse.Center = new Point(x, y);
                    }
                }
            }
            return finalSize;
        }
    }
}
